import {activityDialogListApi} from '@/services/api/activity';

import store from '@/store';
import lscache from 'lscache';


const initState = () => {
  return {
    //true 未展示过，可以展示, false 不展示
    // isOpen: true,
    userCacheName: '',
    isOpen: false,
    activityList: [],
  };
};

const getters = {
  globalActivityList: state => {
    return state.activityList;
  },
  isGlobalActivity: state => {
    return !!(state.isOpen && state.activityList.length);
  }
};

// actions
const actions = {
  /**
   * 取得全局弹窗活动信息
   * @param commit
   * @returns {Promise<{result: *, data: *}>}
   */
  async [types.GET_GLOBAL_ACTIVITY]({commit}) {
    const [result, data] = await activityDialogListApi();

    if (result) {
      commit(types.GET_GLOBAL_ACTIVITY_SUCCESS, data);
    }

    return {result, data};
  },
};

// mutations
const mutations = {
  [types.CLOSE_GLOBAL_ACTIVITY](state) {
    state.isOpen = false;
  },
  [types.GET_GLOBAL_ACTIVITY_SUCCESS](state, data) {
    state.userCacheName = `${consts.CACHE_CLOSE_TODAY_DIALOG}-${store.state.user.id}`;
    const isOpenedToday = !!lscache.get(state.userCacheName);

    state.activityList = data;

    if (!isOpenedToday) {
      state.isOpen = true;
      lscache.set(state.userCacheName, true, 60 * 24);
    }
  },
  [types.LOGOUT](state) {
    Object.assign(state, initState());
  }
};

export default {
  state: initState,
  getters,
  actions,
  mutations,
};
